// pages/order/my-order/my-order.js
var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
var emptyUtil = require('../../templates/empty/empty.js')
var that

const MAX_PAGE_COUNT = 30
const FAIL_MSG = "加载失败,请稍候重试~"
const EMPTY_MSG = "暂无内容，快去逛逛吧~"

const OPT_TYPE_DELETE = "delete"
const OPT_TYPE_CANCEL = "cancel"
const OPT_TYPE_LOGISTICS = "logistics"
const OPT_TYPE_ONLINEPAY = "onlinepay"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderLists: [], //[0]全部、[1]待确认、[2]待发货、[3]待收货、[4]已结束

    orderParamList: [{
      "orderStatus": "all",
      "pageNum": 0,
      "enableLoadMore": true,
      "isLoadingMore": false,
      'emptyParam': {
        'emptyStatus': 0
      },
    }, {
      "orderStatus": "noConfirm",
      "pageNum": 0,
      "enableLoadMore": true,
      "isLoadingMore": false,
      'emptyParam': {
        'emptyStatus': 0
      },
    }, {
      "orderStatus": "noSend",
      "pageNum": 0,
      "enableLoadMore": true,
      "isLoadingMore": false,
      'emptyParam': {
        'emptyStatus': 0
      },
    }, {
      "orderStatus": "noTake",
      "pageNum": 0,
      "enableLoadMore": true,
      "isLoadingMore": false,
      'emptyParam': {
        'emptyStatus': 0
      },
    }, {
      "orderStatus": "end",
      "pageNum": 0,
      "enableLoadMore": true,
      "isLoadingMore": false,
      'emptyParam': {
        'emptyStatus': 0
      },
    }], //五组
     
    curTopBarIndex: 0 //当前选中
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this
    uiUtil.showLoading("加载中..")
    this.requestMyOrderList(0)
  },

  // 更改已支付订单的状态
  havePaidOrders(res){
    let index;
    for (index in that.data.orderLists){
      let list = that.data.orderLists[index];
      let listOne = list.filter(function (e) {
        return e.orderId === res;
      });
      if (listOne[0].orderStatus == "noPay") { //更改已付款的订单状态显示
        let listIndex=list.indexOf(listOne[0]);
        that.data.orderLists[index][listIndex].optBtnList = [];
        that.data.orderLists[index][listIndex].orderStatus = "noSend";
        that.setData({
          orderLists: that.data.orderLists
        })
      }
    }
  },

  /**
   * 滑动到底部
   */
  onReachBottom: function() {
    this.requestMyOrderList(this.data.curTopBarIndex)
  },
  onShareAppMessage: function (res) {
    return util.handleShareApp()
  },
  /**
   * 选项卡切换
   */
  onSwithTabBar(e) {
    var index = e.target.dataset.current;
    if (index == this.data.curTopBarIndex) {
      return
    }

    this.setData({
      curTopBarIndex: index
    })
    var orderList = this.data.orderLists[index] || []
    if (orderList.length == 0) {
      this.requestMyOrderList(index)
    }
  },


  /**
   * 操作按钮点击
   */
  onOptBtnClick(e) {
    var dataset = e.currentTarget.dataset;
    var btnType = dataset.btntype
    var orderId = dataset.orderid
    var index = dataset.index
    
    if (OPT_TYPE_DELETE == btnType) { //删除
      wx.showModal({
        title: '删除订单',
        content: '确定要删除该订单吗?',
        showCancel: true,
        success(res) {
          if (res.confirm) {
            that.requestDeleteOrder(orderId, index)
          }
        }
      })
    } else if (OPT_TYPE_CANCEL == btnType) { //取消
      wx.showModal({
        title: '取消订单',
        content: '确定要取消该订单吗?',
        showCancel: true,
        success(res) {
          if (res.confirm) {
            that.requestCancelOrder(orderId, index)
          }
        }
      })
    } else if (OPT_TYPE_LOGISTICS == btnType) { //查看物流信息
      wx.navigateTo({
        url: '../logistics/logistics?orderId=' + orderId,
      })
    } else if (OPT_TYPE_ONLINEPAY == btnType){ //线上支付
      wx.navigateTo({
        url: '/pages/order/online-order/online-order?orderId=' + orderId,
      })
    }
  },


  /**
   * 请求删除订单
   */
  requestDeleteOrder(orderId, index) {
    uiUtil.showLoading("请稍候..")
    httpUtil.PostRequest("modify_order_status", {
      orderId: orderId,
      toStatus: 'delete'
    }, {
      success(res) {
        uiUtil.showToast("删除订单成功")
        // uiUtil.hideLoading()
        var orderLists = that.data.orderLists
        var curTopBarIndex = that.data.curTopBarIndex
        var allOderList = orderLists[curTopBarIndex] || [];
        allOderList.splice(index, 1);
        orderLists[curTopBarIndex] = allOderList
        that.setData({
          orderLists: orderLists
        })
      },
      fail(code, res) {
        uiUtil.showToast(res||"删除失败,请稍候重试.")
      },
      complete() {
      }
    })
  },


  /**
   * 请求取消订单
   */
  requestCancelOrder(orderId, index) {
    uiUtil.showLoading("请稍候..")
    httpUtil.PostRequest("modify_order_status", {
      orderId: orderId,
      toStatus: 'cancel'
    }, {
      success(res) {
        uiUtil.showToast("取消订单成功")
        // uiUtil.hideLoading()
        var orderLists = that.data.orderLists
        var curTopBarIndex = that.data.curTopBarIndex
        var allOderList = orderLists[curTopBarIndex] || [];
        allOderList[index].orderStatus = "end"
        allOderList[index].orderChildStatus = "cancel"
        allOderList[index].optBtnList = [{
          'btnName': '删除订单',
          'btnType': 'delete'
        }]
        orderLists[curTopBarIndex] = allOderList
        that.setData({
          orderLists: orderLists
        })
      },
      fail(code, res) {
        uiUtil.showToast(res||"取消失败,请稍候重试.")
      },
      complete() {}
    })
  },


  /**
   * 获取商品详情
   */
  requestMyOrderList(index) {
    var orderParamList = this.data.orderParamList
    var param = orderParamList[index]
    if (param.pageNum != 0 && (!param.enableLoadMore || param.isLoadingMore)) { //不可加载||正在加载
      return;
    }

    param.pageNum = param.pageNum + 1
    param.isLoadingMore = true
    orderParamList[index] = param

    this.setData({
      'orderParamList': orderParamList
    })

    httpUtil.PostRequest("order_list", {
      orderStatus: param.orderStatus,
      pageNum: param.pageNum,
      pageRows: MAX_PAGE_COUNT
    }, {
      complete() {
        wx.hideLoading()
      },
      success(res) {
        var orderLists = that.data.orderLists;
        var allOderList = orderLists[index] || [];
        var orderParamList = that.data.orderParamList;
        var param = orderParamList[index]
        var datalist = res.orderList || []
        if (param.pageNum == 1) {
          if (datalist.length == 0) { //内容为空
            that.showEmptyView(index)
          } else {
            that.hideView(index)
          }
        }
        allOderList = allOderList.concat(datalist)
        param.enableLoadMore = allOderList.length < res.rowCount
        param.isLoadingMore = false

        orderLists[index] = allOderList
        orderParamList[index] = param
        that.setData({
          'orderLists': orderLists,
          'orderParamList': orderParamList
        })
      },
      fail(code, res) {
        var orderParamList = that.data.orderParamList
        var param = orderParamList[index]
        param.isLoadingMore = false
        param.enableLoadMore = false
        orderParamList[index] = param
        that.setData({
          orderParamList: orderParamList
        })
        if (param.pageNum == 1) {
          var text = emptyUtil.getErrText(code, res, "获取商品信息失败")
          that.showFailView(index, text)
        }
      }
    })
  },


  /**
   * 显示页面为空布局
   */
  showEmptyView(index, text) {
    var orderParamList = that.data.orderParamList
    var param = orderParamList[index]
    param.emptyParam = {
      emptyStatus: 1,
      emptyImgUrl: "/resources/image/img_load_empty.png",
      emptyTitle: text ? text : EMPTY_MSG
    }
    orderParamList[index] = param
    this.setData({
      'orderParamList': orderParamList
    })
  },

  /**
   * 显示页面失败布局
   */
  showFailView(index, text) {
    var orderParamList = that.data.orderParamList
    var param = orderParamList[index]
    param.emptyParam = {
      emptyStatus: 2,
      emptyImgUrl: "/resources/image/img_load_failed.png",
      emptyTitle: text ? text : FAIL_MSG
    }
    this.setData({
      'orderParamList': orderParamList
    })
  },

  /**
   * 隐藏布局
   */
  hideView(index) {
    var orderParamList = that.data.orderParamList
    var param = orderParamList[index]
    param.emptyParam = {
      emptyStatus: 0,
    }
    orderParamList[index] = param
    this.setData({
      'orderParamList': orderParamList
    })
  },

})
